package MySequenceTable;

import java.util.Arrays;

public class MyArrayList {
    public int[] elem;
    public int UsedSize;
    public MyArrayList(){
        this.elem=new int[10];
    }
    //判断顺序表是否为空
    public boolean isFull(){
        if(this.elem.length==this.UsedSize){
            return true;
        }
        return false;
    }
    //向顺序表中添加数据(头插)
    public void addFirst(int data){
        //首先判断顺序表是否满了,另写一个方法,方便后续使用.
        if(isFull()){
            //如果满了,就要扩容,这里就直接写在里面
            this.elem= Arrays.copyOf(this.elem,2*elem.length);
        }
        //头插的思想就是将所有元素向后移动一位
        for(int i=UsedSize-1;i>=0;i--){
            this.elem[i+1]=this.elem[i];
        }
        this.elem[0]=data;
        UsedSize++;
    }
    public void addLast(int data){
        if(isFull()){
            this.elem=Arrays.copyOf(elem,2*elem.length);
        }
        this.elem[UsedSize]=data;
        UsedSize++;
    }
    public void anyAdd(int index,int data){
        if(isFull()){
            this.elem=Arrays.copyOf(elem,2*elem.length);
        }
        try{
            checkIndex(index);
        }catch (indexExecption e){
            e.printStackTrace();
        }
        for(int i= this.UsedSize-1;i>=index;i--){
            this.elem[i+1]=this.elem[i];
        }
        UsedSize++;
    }
    public void show() {
        for (int i = 0; i < UsedSize; i++) {
            System.out.println(i);
        }
    }
    private void checkIndex(int index){
        if(index>this.UsedSize||index<0){
            throw new RuntimeException("index位置不合法");
        }
    }
    public int contain(){
        int count=0;
        for (int i = 0; i < this.UsedSize-1; i++) {

            count++;
        }
        return count;
    }
    public int indexOf(int data){
        for (int i = 0; i < this.UsedSize; i++) {
            if(data==this.elem[i]){
                return i;
            }
        }
        return -1;
    }
    public int findData(int index){
       return this.elem[index];
    }
    public void deleData(int data){
        int num=indexOf(data);
        if(num<0){
            return ;
        }
        for (int i = num; i <UsedSize-1 ; i++) {
            this.elem[i]=this.elem[i+1];
        }
        UsedSize--;
    }
    public void clear(){
        this.UsedSize=0;
    }

    @Override
    public String toString() {
        return "MyArrayList{" +
                "elem=" + Arrays.toString(elem) +
                ", UsedSize=" + UsedSize +
                '}';
    }
}
